//
//  GYHomeViewController.m
//  research
//
//  Created by 章鱼 on 17/3/27.
//  Copyright © 2017年 simon. All rights reserved.
//

#import "GYHomeViewController.h"
#import "SDCycleScrollView.h"
#import "GYQuestionCell.h"
#import "GYNewsCell.h"
#import "YGHttpManager.h"
#import "GYBanerModel.h"
#import "GYUserInfoViewController.h"
#import "GYNewsListModel.h"
#import "GYNewsInfoModel.h"
#import "GYInfoViewController.h"
#import "XZImageTextButton.h"
#import "GYQuestInfoModel.h"
#import "GYLoginViewController.h"
#import "GYNewsInfoModel.h"

#import "XFWkwebView.h"

@interface GYHomeViewController ()<
SDCycleScrollViewDelegate
,UITableViewDataSource,
UITableViewDelegate>
@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) XZImageTextButton *questionButton;
@property (nonatomic, strong) XZImageTextButton *newsButton;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) NSMutableArray *bannerImageArray;
@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, strong) NSMutableArray *urlArray;
@property (nonatomic, strong) NSMutableArray *infoArray;
@property (nonatomic, strong) NSMutableArray *noMoreArray;
@property (nonatomic, assign) NSInteger cpage;//每页显示条数
@property (nonatomic, assign) NSInteger psize;//页数
@property (nonatomic, assign) GYHomeInfoStytleType type;

@end

@implementation GYHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self basicSetup];
    [self initCycleScrollView];
    [self loadNewData];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self addRightButtonItemWithTitle:@"" backImg:@"navigation bar_-details_normal"];
}

- (void)rightButtonItemClick {
    [super rightButtonItemClick];
    [self userIsLogin];
}

#pragma mark - action 判断是否登录
- (void)userIsLogin {
    
    [[YGHttpManager defaultManager] fetchGetUserIsloginWithtoken:[[GYConfigDBManager defaultManager] gyToken] success:^(id responseObj) {
        //重新登录
        if ([[responseObj objectForKey:@"status"] integerValue] == 0) {
            if ([[GYConfigDBManager defaultManager] userInformation].userName && [[GYConfigDBManager defaultManager] userInformation].password) {
                [[YGHttpManager defaultManager] fetchGetUserLoginWithuserName:[[GYConfigDBManager defaultManager] userInformation].userName password:[[GYConfigDBManager defaultManager] userInformation].password success:^(id responseObj) {
                    GYCommonModel *commonmodel = [GYCommonModel mj_objectWithKeyValues:responseObj];
                    if ([[responseObj objectForKey:@"status"] integerValue] == 0) {
                        [VBAlertView showTextHUD:commonmodel.message];
                        return ;
                    }
                    [[GYConfigDBManager defaultManager] setLogin:YES];
                    [[GYConfigDBManager defaultManager] setGYToken:[commonmodel.data objectForKey:@"token"]];
                    GYUserInfoModel *model = [GYUserInfoModel mj_objectWithKeyValues:[commonmodel.data objectForKey:@"user"]];
                    [[GYConfigDBManager defaultManager] setUserInformation:model];
                    
                    GYUserInfoViewController *userCtrl = [[GYUserInfoViewController alloc] init];
                    userCtrl.hidesBottomBarWhenPushed = YES;
                    userCtrl.tabBarController.tabBar.hidden = YES;
                    [self.navigationController pushViewController:userCtrl animated:YES];
                    
                } failure:^(NSError *error) {
                    
                }];
            }else {
                
                GYLoginViewController *loginCtrl = [[GYLoginViewController alloc] init];
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginCtrl];
                [self presentViewController:nav animated:YES completion:NULL];
            }
            return ;
        }
        GYUserInfoViewController *userCtrl = [[GYUserInfoViewController alloc] init];
        userCtrl.hidesBottomBarWhenPushed = YES;
        userCtrl.tabBarController.tabBar.hidden = YES;
        [self.navigationController pushViewController:userCtrl animated:YES];
        
    } failure:^(NSError *error) {
        
    }];
}
//获取首页轮播图
- (void)startGetBanerList {
    [[YGHttpManager defaultManager] fetchGetBannersuccess:^(id responseObj) {
        GYCommonModel *model = [GYCommonModel mj_objectWithKeyValues:responseObj];
        _bannerImageArray = [NSMutableArray array];
        _titleArray = [NSMutableArray array];
        _urlArray = [NSMutableArray array];
        for (NSDictionary *dic in model.data) {
            GYBanerModel *model = [GYBanerModel mj_objectWithKeyValues:dic];
            [_bannerImageArray addObject:model.img];
            [_titleArray addObject:model.title];
            [_urlArray addObject:model.link];
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.cycleScrollView.imageURLStringsGroup = _bannerImageArray;
            self.cycleScrollView.titlesGroup = _titleArray;
        });
        
    } failure:^(NSError *error) {
        
    }];
}
//问卷列表
- (void)startGetQuestList {
    [[YGHttpManager defaultManager] fetchGetQueslistWithPage:_cpage Pagesize:_psize success:^(id responseObj) {
        GYCommonModel *commonmodel = [GYCommonModel mj_objectWithKeyValues:responseObj];
        GYNewsListModel *model = [GYNewsListModel mj_objectWithKeyValues:commonmodel.data];
        self.noMoreArray = [NSMutableArray arrayWithArray:model.list];
        if (self.noMoreArray.count ==0) {
            [_mainScrollView.mj_footer endRefreshingWithNoMoreData];
        }
        
        if (_cpage == 1) {
            [self.infoArray removeAllObjects];
        }
        [self.infoArray addObjectsFromArray:model.list];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}
//新闻列表
- (void)startGetNewsList {
    [[YGHttpManager defaultManager] fetchGetNewsListWithPage:_cpage Pagesize:_psize success:^(id responseObj) {
        GYCommonModel *commonmodel = [GYCommonModel mj_objectWithKeyValues:responseObj];
        GYNewsListModel *model = [GYNewsListModel mj_objectWithKeyValues:commonmodel.data];
        self.noMoreArray = [NSMutableArray arrayWithArray:model.list];
        if (self.noMoreArray.count ==0) {
            [_mainScrollView.mj_footer endRefreshingWithNoMoreData];
        }
        
        if (_cpage == 1) {
            [self.infoArray removeAllObjects];
        }
        [self.infoArray addObjectsFromArray:model.list];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

- (void)basicSetup {
    [self initNavBarWithTitle:@"调查星" tintColor:[UIColor orz_mainColor]];
    [self.navBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                         [UIColor whiteColor],NSForegroundColorAttributeName,
                                         [UIFont boldSystemFontOfSize:20],
                                         NSFontAttributeName,
                                         nil]];
    [self.view setBackgroundColor:[UIColor orz_globalBackground]];
    _mainScrollView = [[UIScrollView alloc] init];
    [self.view addSubview:_mainScrollView];
    _mainScrollView.backgroundColor = [UIColor orz_globalBackground];
    _mainScrollView.showsHorizontalScrollIndicator = NO;
    _mainScrollView.showsVerticalScrollIndicator = NO;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    _mainScrollView.mj_header = header;
    
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    _mainScrollView.mj_footer = footer;
    footer.refreshingTitleHidden = YES;
    [footer setTitle:@"" forState:MJRefreshStateIdle];

    [_mainScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(64.f);
        make.bottom.mas_equalTo(0.f);
        make.left.mas_equalTo(0.f);
        make.right.mas_equalTo(0.f);
    }];
    
    _type = GYQuestInfoType;
}

#pragma mark - 上拉刷新，下拉加载更多
- (void)loadNewData {

    if (_questionButton.selected) {
        self.cpage = 1;
        self.psize = 4;
        [self startGetQuestList];
    }else{
        self.cpage = 1;
        self.psize = 8;
        [self startGetNewsList];
    }
    [self startGetBanerList];
    [_mainScrollView.mj_header endRefreshing];
    [_mainScrollView.mj_footer endRefreshing];
}
- (void)loadMoreData {
    self.cpage = self.cpage + 1;
    if (_questionButton.selected) {
        
        [self startGetQuestList];
    }else{
        [self startGetNewsList];
    }
    [self startGetBanerList];
    [_mainScrollView.mj_header endRefreshing];
    [_mainScrollView.mj_footer endRefreshing];
    
}
- (void)initCycleScrollView {
    
    _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, (175+59)*ADJUST_SCREEN_HEIGHT_SCALE)];
    _backView.backgroundColor = [UIColor orz_globalBackground];
    [_mainScrollView addSubview:_backView];
    
    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 175*ADJUST_SCREEN_HEIGHT_SCALE) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    
    _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    _cycleScrollView.titlesGroup = _titleArray;
    _cycleScrollView.currentPageDotColor = [UIColor whiteColor];
    [_backView addSubview:_cycleScrollView];
    
    UIView * buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, 175*ADJUST_SCREEN_HEIGHT_SCALE, SCREEN_WIDTH, 49*ADJUST_SCREEN_HEIGHT_SCALE)];
    [_backView addSubview:buttonView];
    
    buttonView.backgroundColor = [UIColor  colorWithHex:@"484a57" alpha:1];
    
    _questionButton = [XZImageTextButton buttonWithType:UIButtonTypeCustom];
    _questionButton.frame =CGRectMake(0, 0, SCREEN_WIDTH/2, 49*ADJUST_SCREEN_HEIGHT_SCALE);
    _questionButton.selected = YES;
    [_questionButton setImage:[UIImage imageNamed:@"home_button_questionnaire"] forState:UIControlStateNormal];
    [_questionButton setImage:[UIImage imageNamed:@"home_button_questionnaire_selected"] forState:UIControlStateSelected];
    [_questionButton setTitle:@"最新问卷" forState:UIControlStateNormal];
    _questionButton.titleLabel.font = [UIFont systemFontOfSize:12.f];
    [buttonView addSubview:_questionButton];
    [_questionButton setTitleColor:[UIColor colorWithHex:@"ffcf5c" alpha:1] forState:UIControlStateNormal];
    [_questionButton addTarget:self action:@selector(questionClick:) forControlEvents:UIControlEventTouchUpInside];
    [_questionButton setButtonTitleWithImageAlignment:UIButtonTitleWithImageAlignmentDown];
    
    _newsButton = [[XZImageTextButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, 49*ADJUST_SCREEN_HEIGHT_SCALE)];
    [buttonView addSubview:_newsButton];
    [_newsButton setTitle:@"热点新闻" forState:UIControlStateNormal];
    _newsButton.titleLabel.font = [UIFont systemFontOfSize:12];

    [_newsButton setImage:[UIImage imageNamed:@"home_button_news"] forState:UIControlStateNormal];
    [_newsButton setImage:[UIImage imageNamed:@"home_button_news_selected"] forState:UIControlStateSelected];
    [_newsButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_newsButton setTitleColor:[UIColor colorWithHex:@"ffcf5c" alpha:1] forState:UIControlStateSelected];
    [_newsButton addTarget:self action:@selector(newsClick:) forControlEvents:UIControlEventTouchUpInside];
    [_newsButton setButtonTitleWithImageAlignment:UIButtonTitleWithImageAlignmentDown];

    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-0.5, 0, 1, 49*ADJUST_SCREEN_HEIGHT_SCALE)];
    [buttonView addSubview:lineView];
    lineView.backgroundColor = [UIColor  colorWithHex:@"5e6172" alpha:1];
    
    UIView * emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, (175+49)*ADJUST_SCREEN_HEIGHT_SCALE, SCREEN_WIDTH, 10)];
    [emptyView setBackgroundColor:[UIColor orz_globalBackground]];
    [_backView addSubview:emptyView];
}

#pragma mark - UI
- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor orz_globalBackground];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.scrollEnabled = NO;
        [_mainScrollView addSubview:_tableView];
        [self initTableviewUI];
        _tableView.estimatedRowHeight=120.0f;
        _tableView.rowHeight=UITableViewAutomaticDimension;
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView registerClass:[GYQuestionCell class] forCellReuseIdentifier:@"GYQuestion"];
        [_tableView registerClass:[GYNewsCell class] forCellReuseIdentifier:@"NewsCell"];
        
        [_tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
        
        [self.tableView reloadData];
    }
    return _tableView;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"contentSize"]) {
        _mainScrollView.contentSize =CGSizeMake(SCREEN_WIDTH, (175+49)*ADJUST_SCREEN_HEIGHT_SCALE+self.tableView.contentSize.height);
        self.tableView.frame = CGRectMake(0, (175+49)*ADJUST_SCREEN_HEIGHT_SCALE, SCREEN_WIDTH, self.tableView.contentSize.height);
    }else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
    NSLog(@"%f",self.tableView.contentSize.height);
}


- (void)initTableviewUI {

}
#pragma mark - tableView的代理方法


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_newsButton.selected) {
        
        GYNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell" forIndexPath:indexPath];
        if (indexPath.row%2 == 0) {
            cell.backgroundColor = [UIColor colorWithHex:@"f9f5f5" alpha:1];
        }else{
            cell.backgroundColor = [UIColor colorWithHex:@"f3f3f3" alpha:1];
        }
        if (_infoArray.count > indexPath.row) {
            GYNewsInfoModel *model = [GYNewsInfoModel mj_objectWithKeyValues:_infoArray[indexPath.row]];
            [cell updateCellWithData:model];
        }
        return cell;
    }
    
    GYQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GYQuestion" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor orz_globalBackground];
    if (_infoArray.count > indexPath.row) {
        GYQuestInfoModel *model = [GYQuestInfoModel mj_objectWithKeyValues:_infoArray[indexPath.row]];
        [cell updateCellWithData:model];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_type == GYQuestInfoType) {
        GYQuestInfoModel *model =[GYQuestInfoModel mj_objectWithKeyValues:_infoArray[indexPath.row]];
        if (model.status == 1) {
            
            GYInfoViewController *infoCtrl = [[GYInfoViewController alloc] initWithTitle:@"问卷详情" videoType:GYQuestInfoType statuId:model.id];
            infoCtrl.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:infoCtrl animated:YES];
        }else {
            if (model.status == 0) {
                
                [VBAlertView showTextHUD:@"问卷暂未开放"];
            }
            if (model.status == 2) {
                
                [VBAlertView showTextHUD:@"问卷已结束"];
            }
        }
        
    }else{
        GYNewsInfoModel *model =[GYNewsInfoModel mj_objectWithKeyValues:_infoArray[indexPath.row]];
 
        XFWkwebView *webView = [[XFWkwebView alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:webView];
        [webView loadWebURLSring:model.link];
        [self presentViewController:nav animated:YES completion:nil];
  
    }
}

- (void)questionClick:(UIButton *)btn {

    if (!btn.selected) {
        _type = GYQuestInfoType;
        btn.selected = YES;
        _newsButton.selected = NO;
        [_questionButton setTitleColor:[UIColor colorWithHex:@"ffcf5c" alpha:1] forState:UIControlStateNormal];
        [_newsButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self loadNewData];
        
    }
}

- (void)newsClick:(UIButton *)btn {

    if (!btn.selected) {
        _type = GYNewsInfoType;
        btn.selected = YES;
        _questionButton.selected = NO;
        [_questionButton setTitleColor:[UIColor colorWithHex:@"ffffff" alpha:1] forState:UIControlStateNormal];
        [_newsButton setTitleColor:[UIColor colorWithHex:@"ffcf5c" alpha:1] forState:UIControlStateNormal];
        [self loadNewData];
    }
}

- (void)dealloc{
    [self.tableView removeObserver:self forKeyPath:@"contentSize"];
}

//banner图点击事件（h5）
#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSString * style =_urlArray[index];
    style = [style substringToIndex:6];//截取掉下标7之后的字符串
    NSString *Number = [[_urlArray[index] componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet]] componentsJoinedByString:@""];

    if ([style isEqualToString:@"sdetai"]) {
        //跳转问卷详情
        GYInfoViewController *infoCtrl = [[GYInfoViewController alloc] initWithTitle:@"问卷详情" videoType:GYQuestInfoType statuId:[Number intValue]];
        infoCtrl.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoCtrl animated:YES];
    }else {
    
        
        [[YGHttpManager defaultManager] fetchGetNewsInfoWithNewsId:[Number intValue] success:^(id responseObj) {
            GYCommonModel *model = [GYCommonModel mj_objectWithKeyValues:responseObj];
            GYNewsInfoModel * newsModel = [GYNewsInfoModel mj_objectWithKeyValues:model.data];
            XFWkwebView *webView = [[XFWkwebView alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:webView];
            [webView loadWebURLSring:newsModel.link];
            [self presentViewController:nav animated:YES completion:nil];
            
        } failure:^(NSError *error) {
            
        }];
    }
}

- (NSMutableArray *)infoArray {
    
    if (!_infoArray) {
        _infoArray = [NSMutableArray array];
    }
    return _infoArray;
}

- (NSMutableArray *)noMoreArray {
    
    if (!_noMoreArray) {
        _noMoreArray = [NSMutableArray array];
    }
    return _noMoreArray;
}

@end
